package com.baiyinet.ui.login;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiyinet.BuildConfig;
import com.baiyinet.MyApp;
import com.baiyinet.R;
import com.baiyinet.biz.AdInfo;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.di.DaggerScope;
import com.baiyinet.di.Injector;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.AppInfo;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.Utils;
import com.bumptech.glide.Glide;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;
import java.util.Random;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;


@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(LoginAdActivity.class)
@EActivity(R.layout.activity_login_ad)
public class LoginAdActivity extends AppCompatActivity {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;

    @ViewById(R.id.open_ad_tv_num)
    TextView mNumText;
    @ViewById(R.id.open_ad_layout_backgroud)
    RelativeLayout mOpenAdLayout;

    @StringRes(R.string.network_disabled)
    String strNetworkDisabled;
    @StringRes(R.string.api_error)
    String strApiError;

    private String url;
    private final int TO_NEXT_DELAY_BY_SECOND_CODE = 555;
    private int second = 5;

    @AfterInject
    void initLoginDI() {
        Injector.initLoginAdActivityComponent().inject(this);
    }

    @AfterViews
    void initData() {
        mApiHelper.getAppInfo(new AppInfoSubscriber());
    }

    private void initAdInfo(AdInfo adInfo) {

        ArrayList<AdInfo.AdDetail> data = adInfo.getData();
        int total = adInfo.getTotal();
        String imgUrl;
        if (total > 1) {
            Random random = new Random();
            int randomIndex = random.nextInt(data.size());
            url = data.get(randomIndex).getUrl();
            imgUrl = data.get(randomIndex).getImage();
        } else {
            url = data.get(0).getUrl();
            imgUrl = data.get(0).getImage();
        }

        if (!url.startsWith("http") && !url.startsWith("#")) {
            url = BuildConfig.ENDPOINT + url;
        }

        if (!imgUrl.startsWith("#") && !imgUrl.startsWith("http")) {
            imgUrl = BuildConfig.ENDPOINT + imgUrl;
        }

        ImageView imageView = new ImageView(this);

        Glide
                .with(this)
                .load(imgUrl)
                .centerCrop()
                .into(imageView);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);

        mOpenAdLayout.addView(imageView, params);
        handler.sendEmptyMessageDelayed(TO_NEXT_DELAY_BY_SECOND_CODE, 1000);
    }

    private void initBaiduAd() {
        toNextAction();
    }

    @Click(R.id.open_ad_layout_jump)
    void toNextAction() {
        handler.removeMessages(TO_NEXT_DELAY_BY_SECOND_CODE);

        IntentUtils.toLogin(this);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == TO_NEXT_DELAY_BY_SECOND_CODE) {
                second--;
                if (second > 0) {
                    mNumText.setText(second + "");
                    handler.sendEmptyMessageDelayed(TO_NEXT_DELAY_BY_SECOND_CODE, 1000);
                } else {
                    toNextAction();
                }
            }
        }
    };

    class AppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(strApiError);
        }

        @Override
        public void onNext(AppInfo appInfo) {
            mCurrentUser.setAppInfo(appInfo);

            if ("Show".equals(appInfo.ShowStartAd)) {
                mApiHelper.startAd(new StartAdSubscriber());
            } else if ("Hide".equals(appInfo.ShowStartAd)) {
                toNextAction();
            }
        }
    }

    class StartAdSubscriber extends Subscriber<AdInfo> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(strApiError);
        }

        @Override
        public void onNext(AdInfo adInfo) {
            if (adInfo != null) {
                if (adInfo.getData() != null && adInfo.getTotal() > 0) {
                    initAdInfo(adInfo);
                } else {
                    initBaiduAd();
                }
            }
        }
    }
}
